package com.element.security.server.global;

import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2RequestValidator;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @auther WuJun.Zhang
 * @date 2022/2/20 下午3:04
 */
@Component(value = "globalOAuth2RequestValidator")
public class GlobalOAuth2RequestValidator implements OAuth2RequestValidator {

    @Override
    public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException {
        if (client.isScoped()) {
            this.validateScope(authorizationRequest.getScope(), client.getScope());
        }
    }

    @Override
    public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException {
        if (client.isScoped()) {
            this.validateScope(tokenRequest.getScope(), client.getScope());
        }
    }

    private void validateScope(Set<String> requestScopes, Set<String> clientScopes) {
        if (clientScopes != null && !clientScopes.isEmpty()) {
            for (String scope : requestScopes) {
                if (!clientScopes.contains(scope)) {
                    throw new InvalidScopeException("Invalid scope: " + scope, clientScopes);
                }
            }
        } else {
            throw new InvalidScopeException("无法访问该领域请求");
        }
        if (requestScopes.isEmpty()) {
            throw new InvalidScopeException("Empty scope (either the client or the user is not allowed the requested scopes)");
        }
    }
}
